package com.atguigu.serviceedu.service.impl;

import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.serviceedu.entity.EduChapter;
import com.atguigu.serviceedu.entity.EduSubject;
import com.atguigu.serviceedu.entity.EduVideo;
import com.atguigu.serviceedu.entity.chapter.ChapterVo;
import com.atguigu.serviceedu.entity.chapter.VideoVo;
import com.atguigu.serviceedu.entity.subject.OneSubject;
import com.atguigu.serviceedu.entity.subject.TwoSubject;
import com.atguigu.serviceedu.mapper.EduChapterMapper;
import com.atguigu.serviceedu.service.EduChapterService;
import com.atguigu.serviceedu.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author zzc
 * @since 2022-09-16
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService videoService;

    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        //1 先查询一级分类
        QueryWrapper<EduChapter> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("course_id",courseId);
        List<EduChapter> oneSubjectList = baseMapper.selectList(wrapperOne);
        //2 再查询二级分类
        QueryWrapper<EduVideo> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.eq("course_id",courseId);
        List<EduVideo> twoSubjectList = videoService.list(wrapperTwo);
        //3 封装一级分类
        List<ChapterVo> finalList = new ArrayList<>();
        for (EduChapter eduChapter : oneSubjectList) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter, chapterVo);
            finalList.add(chapterVo);
            //4 封装二级分类
            List<VideoVo> videoVoList =new ArrayList<>();
            for (EduVideo eduVideo:twoSubjectList) {
                VideoVo videoVo = new VideoVo();
                if(eduVideo.getChapterId().equals(eduChapter.getId())){
                    BeanUtils.copyProperties(eduVideo, videoVo);
                    videoVoList.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVoList);
        }
        return finalList;
    }

    @Override
    public List<ChapterVo> getChapter(String id) {
        return null;
    }

    @Override
    public void deleteChapter(String chapterId) {
        //根据id查询是否存在视频，如果有则提示用户尚有子节点
       QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
       wrapper.eq("chapter_id",chapterId);
       if(videoService.count(wrapper) > 0){//查询出小节 不能删除
           throw new GuliException(20001,"无法删除");
       }else {
           baseMapper.deleteById(chapterId);
       }
    }
}
